package it.blueocean.acanto.web.platform.components.repeaters;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractToolbar;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

@SuppressWarnings("unchecked")
class AcantoNumRecordsPerPageToolbar extends AbstractToolbar
{
	private static final long serialVersionUID = -6516636913950717354L;

	protected AcantoNumRecordsPerPageToolbar(DataTable<?> table)
	{
		super(table);
	}

	protected AcantoNumRecordsPerPageToolbar(DataTable table, int initialRecordsPerPage)
	{
		super(table);

		// add(HeaderContributor.forCss("customAcanto.css")); // TODO
		WebMarkupContainer spanLabel = new WebMarkupContainer("spanLabel");
		add(spanLabel);
		spanLabel.add(new SimpleAttributeModifier("colspan", String.valueOf(getTable().getColumns().length - 1)));
		
		Label numOfRecordLabel = new Label("pagingLabel","records per page");
		spanLabel.add(numOfRecordLabel);
		
		WebMarkupContainer spanComboBox = new WebMarkupContainer("spanComboBox");
		add(spanComboBox);
		spanComboBox.add(getUsersPerPageSelect(initialRecordsPerPage));
		
		getTable().setRowsPerPage(initialRecordsPerPage);
	}

	private List<Integer> getValuesForSelect(int initial)
	{
		Set<Integer> set = new HashSet<Integer>();
		set.add(10);
		set.add(20);
		set.add(50);
		set.add(100);
		set.add(initial);
		List<Integer> values = new ArrayList<Integer>(set);
		Collections.sort(values);
		return values;
	}

	private DropDownChoiceWithAjaxIndicator getUsersPerPageSelect(final int initial)
	{
		final IModel pagingvalues = new AbstractReadOnlyModel()
		{
			private static final long serialVersionUID = 1L;

			@Override
			public Object getObject()
			{
				List<Integer> values = getValuesForSelect(initial);
				return values;
			}
		};

		final DropDownChoiceWithAjaxIndicator result = new DropDownChoiceWithAjaxIndicator("pagingSelect", new PropertyModel(getTable(), "rowsPerPage"), pagingvalues, this);
		
		result.add(new AjaxFormComponentUpdatingBehavior("onchange")
		{
			private static final long serialVersionUID = 1L;

			@Override
			protected void onUpdate(AjaxRequestTarget target)
			{
				target.addComponent(getTable());
			}
		});
		
		return result;
	}

	@Override
	public boolean isVisible()
	{
		return (getTable().getRowCount() > 1);
	}

}
